<template>
  <a-spin :spinning="loadingTreeData" class="h100">
    <a-tree
      show-icon
      class="departmentTree"
      :tree-data="treeData"
      :selected-keys="selectedOrgId"
      :replaceFields="replaceFields"
      :autoExpandParent="false"
      :expanded-keys="expandedKeys"
      @select="onSelect"
      @expand="onExpand"
    >
      <a-spin></a-spin>
      <i slot="firm" class="iconfont icon-gongsiqiye"></i>
      <i slot="bumen1" class="iconfont icon-bumen1"></i>
      <template slot="bumen">
        <i class="iconfont icon-bumen"></i>
      </template>
      <template #title="item">
        <span
          class="treeNodeName"
        ><table-ellipsis :tableEllipsisIsTurnLine="false" :text="item.name"></table-ellipsis
        ></span>
        <a-dropdown v-if="enableOrgActions.length">
          <a class="ant-dropdown-link actionTools" @click.stop> <span>...</span></a>
          <template #overlay>
            <a-menu
              @click="
                ({ key }) => {
                  doDepartment(key, {
                    id: item.dataRef.id,
                    name: item.dataRef.name,
                    parentId: item.dataRef.parentId ? item.dataRef.parentId : null,
                    remark: item.dataRef.remark,
                  })
                }
              "
              class="departmentTreeDropdown"
            >
              <a-menu-item v-for="menuItem in enableOrgActions" :key="menuItem.id">{{ menuItem.title }}</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-tree>
  </a-spin>
</template>
<script>
  import { mapState } from 'vuex'
  import { managePerms } from '@/config/permission/index'
  import orgApi from '@/api/modules/system/org'
  import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
  export default {
    components: {
      tableEllipsis
    },
    computed: {
      ...mapState({
        treeData: (state) => state.org.treeData,
        selectedOrgId: (state) => {
          return state.org.selectedOrg ? [state.org.selectedOrg.id] : null
        }
      }),
      enableOrgActions () {
        return this.orgActions.filter((item) => {
          if (!item.auth) {
            return true
          }
          return this.$hasPermission(item.auth)
        })
      }
    },
    data () {
      const _this = this
      return {
        managePerms,
        replaceFields: {
          title: 'name',
          children: 'childOrganizations',
          key: 'id'
        },
        expandedKeys: [],
        loadingTreeData: false,
        orgActions: [
          {
            id: 'addUser',
            title: _this.$t('new') + _this.$t('user'),
            auth: [managePerms.user.add]
          },
          {
            id: 'addOrg',
            title: _this.$t('new') + _this.$t('org'),
            auth: [managePerms.organization.add]
          },
          {
            id: 'editOrg',
            title: _this.$t('edit') + _this.$t('org'),
            auth: [managePerms.organization.edit]
          },
          {
            id: 'deleteOrg',
            title: _this.$t('delete') + _this.$t('org'),
            auth: [managePerms.organization.delete]
          }
        ]
      }
    },
    created () {
      this.getData()
    },
    methods: {
      getData () {
        this.loadingTreeData = true
        this.$store
          .dispatch('getTreeData')
          .then(() => {
            this.expandedKeys = [...this.selectedOrgId]
          })
          .catch((err) => {
            console.log(err, '获取组织数据失败')
          })
          .finally(() => {
            this.loadingTreeData = false
          })
      },
      onSelect (selectedKeys, info) {
        const { dataRef } = info.node._props
        this.$store.commit('SET_SELECTED_ORG', {
          id: dataRef.id,
          name: dataRef.name,
          parentId: dataRef.parentId,
          remark: dataRef.remark
        })
      },
      onExpand (expandedKeys) {
        this.expandedKeys = expandedKeys
      },
      doDepartment (key, data) {
        if (this[key]) {
          this[key](data)
          return
        }
        this.$store.commit('SET_SELECTED_ORG', data)
        this.$emit('clickorg', key)
      },
      // 批量删除
      deleteOrg (record) {
        const vm = this
        this.$confirm({
          title: vm.$t('deleteOrganization'),
          content: vm.$t('deleteOrgTip').replace('__CONTENT__', '（' + record.name + '）'),
          class: 'confirmStyle',
          width: 378,
          onOk () {
            orgApi.deleteOrg({ ids: [record.id] }).then(() => {
              vm.$message.success(vm.$t('successfullyDelete'))
              vm.$store.commit('SET_SELECTED_ORG', null)
              vm.getData() // 刷新页面
            })
          },
          onCancel () {}
        })
      }
    }
  }
</script>
<style lang="less">
  .departmentTree {
    li {
      position: relative;
    }

    .ant-tree-node-content-wrapper {
      display: block;
      width: 100%;
      position: relative;
      height: 36px;
      color: @color333 !important;
      &:hover,
      &.ant-tree-node-selected {
        background-color: @blockHoverBgColor !important;
        color: @blockHoverTextColor !important;
      }
    }
    .ant-dropdown {
      top: 25px !important;
    }
    .ant-tree-title {
      display: inline-block;
      width: calc(100% - 60px);
      .treeNodeName {
        display: inline-block;
        max-width: 100%;
        overflow: hidden;
      }
    }
  }
  .departmentTreeDropdown {
    padding: 0 !important;
    .ant-dropdown-menu-item {
      padding: 5px 12px;
    }
  }
</style>
<style scoped lang="less">
  .departmentTree {
    .ant-tree-node-content-wrapper:hover {
      .actionTools {
        display: block;
      }
    }
  }
  .departmentTreeTitle {
    position: relative;
    display: inline-block;
  }
  .actionTools {
    position: absolute;
    top: 0;
    right: 20px;
    font-weight: bold;
    display: none;
  }
</style>
